<?php
/**
 * Created by PhpStorm.
 * User: buddha
 * Date: 2021/6/18
 * Time: 17:58
 */

namespace app\admin\controller;


use app\admin\service\AuthService;
use app\admin\service\ManagerRoleService;
use app\admin\service\RoleAuthService;
use app\BaseController;

class Menu extends BaseController
{
    /**
     * @var $service AuthService
     */
    protected $service;

    public function initialize()
    {
        parent::initialize();
        $this->service = new AuthService();
    }

    /**
     * 菜单列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index() {
        // 超管可以获取所有的菜单
        if (request()->userInfo->id == 1) {
            $rows = $this->service->getMenu();
            if (!empty($rows)) {
                $rows = getTree($rows);
            }
            return success('ok', $rows);
        } else {
            // 通过manager_id获取role_id
            $role_id = (new ManagerRoleService())->findOne(request()->userInfo->id);
            if (empty($role_id)) {
                // 没有配置角色
                return fail('无权访问');
            }
            // 通过role_id获取auth_id集合
            $auth_ids = (new RoleAuthService())->getAuthIdByRoleId($role_id);
            if (empty($auth_ids)) {
                return fail('无权访问');
            }
            $rows = (new AuthService())->getMenu($auth_ids);
            return success('ok', $rows);
        }
    }
}